package com.zhanghe.study.io.old;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 操作字符
 */
public class TestReaderWriter {
    public static void main(String[] args) {
        System.out.println("-----------testReader-----------");
        testReader();
        System.out.println();
        copyFile("hello3.txt","hello4.txt");
    }

    /**
     * 测试FileReader的reader方法
     */
    private static void testReader(){
        FileReader reader = null;
        File file = new File("hello3.txt");
        try{
            reader = new FileReader(file);
            char[] c = new char[10];
            int len;
            while((len = reader.read(c)) != -1){
                System.out.print(new String(c,0,len));
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void copyFile(String src,String target){
        FileReader reader = null;
        FileWriter writer = null;
        File srcFile = new File(src);
        File targetFile = new File(target);

        try{
            reader = new FileReader(srcFile);
            writer = new FileWriter(targetFile);
            char[] c = new char[10];
            int len;
            while((len = reader.read(c)) != -1){
                writer.write(c,0,len);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
